import * as THREE from 'three'
import * as Cesium from 'cesium'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { ModelUtils } from '../../components/cesium-three/ModelUtils.js'
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js'

function getDracoLoader({ path }) {
  const dracoLoader = new DRACOLoader()
  dracoLoader.setDecoderPath(path)
  dracoLoader.setDecoderConfig({ type: 'js' })
  return dracoLoader
}
const dracoLoader = getDracoLoader({ path: '/gltf/' })
import { group } from './index.js'

export function loadGltf(url, scene) {
  const { renderer, camera, preRender, postRender } = scene.my

  const loader = new GLTFLoader().setPath('/gltf/')
  loader.setDRACOLoader(dracoLoader)
  loader.load(url, async function (gltf) {
    const model = gltf.scene

    // wait until the model can be added to the scene without blocking due to shader compilation
    // Create a BoxHelper to visualize the bounding box
    const boxHelper = new THREE.BoxHelper(model, 0xff0000) // Red color for the bounding box
    scene.add(boxHelper)
    await renderer.compileAsync(model, camera, scene)

    // ModelUtils.fixXYtoCesium(model)

    const scaleFactor = 1 // 放大两倍
    model.scale.set(scaleFactor, scaleFactor, scaleFactor)

    const boundingBox = new THREE.Box3().setFromObject(model)
    const { y } = boundingBox.min
    model.position.y += -y

    group.add(model)

    /*
    let { longitude, latitude, height } = {
      longitude: 2.024726076130041,
      latitude: 0.6975419291686485,
      // height: 323.3668963019752,
      height: 0,
    }
    longitude = Cesium.Math.toDegrees(2.0245736986836183)
    latitude = Cesium.Math.toDegrees(0.6973668400216658)

    const threeMatrix4 = ModelUtils.getThreeMatrix4FromDegrees(longitude, latitude, height)
    model.applyMatrix4(threeMatrix4)

    */
    // scene.add(model)

    // const { x, y, z } = Cesium.Cartesian3.fromDegrees(longitude, latitude, height)

    // addPoint(scene, x, y, z)

    // Example usage: Add a point at coordinates (10, 10, 10)

    // const g1 = moveToOrigin(model)

    // const { max, min } = g1.aabb
    // const size = new THREE.Vector3().subVectors(max, min)
    // camera.position.set(size.x / 2, size.y / 2, size.z / 2)

    // const controls = new OrbitControls(camera, renderer.domElement)
    // controls.target.set(0, 0, 0)
    // controls.update()

    // scene.add(g1)
    // const radius = camera.position.length()
    // preRender.push(beginRotate(radius))
  })
}
